package crontab

import (
	"fmt"
	"log"
	global2 "longmen/server/config/global"
	"longmen/server/internal/api"
	"longmen/server/internal/services/nami/services"
	"longmen/server/pkg/common/api_models"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_sports"
	"longmen/server/pkg/db/redis/cache"
	"longmen/server/pkg/grpc_client"
	"longmen/server/pkg/protobuf"
	"time"

	"github.com/spf13/cast"
)

func AutoLive() {
	var matchLive []*models_sports.MatchLive
	err := global2.Sport().Model(&models_sports.MatchLive{}).Where("standard_match_status=1 and auto_live = 1 and uhd_link <> ?", "").Find(&matchLive).Error
	if err != nil {
		global2.Log.Error("AutoLive error : ", err)
	}

	for _, v := range matchLive {
		doLive(v)
	}

	var lives []*models_live.Live

	err = global2.Live().Model(&models_live.Live{}).Where("anchorid in (?)", global2.AutoLive.LiveIDs).Scan(&lives).Error
	if err != nil {
		global2.Log.Error("AutoLive error : ", err)
	}
	for _, v := range lives {
		endLive(v.Matchid, v.Categoryid, v.Anchorid)
	}
}

func doLive(match *models_sports.MatchLive) {

	idx, err := db_live.GetIdle(global2.AutoLive.LiveIDs)
	if err != nil {
		global2.Log.Errorf("AuthLive getIdle ERROR:%v", err)
		return
	}
	if idx == 0 {
		global2.Log.Errorf("AuthLive error/No Idle AnchorID:%v", err)
		return
	}
	user, err := mysql.GetUserParam(map[string]interface{}{"id": idx})
	if err != nil {
		global2.Log.Errorf("AuthLive error:%v", err)
		return
	}
	if user.Id <= 0 {
		return
	}

	log.Println("match:", match)
	base := api.Controller{}
	var liveParams api_models.StartLiveReq
	liveParams.Title = fmt.Sprintf("%s vs %s", match.Home, match.Away)
	liveParams.MatchId = int(match.MatchId)
	if match.SportId == _const.FOOT_BALL_SPORT_ID {

		// liveParams.Thumb = thumb_football[*idx]
		liveParams.Thumb = global2.AutoLive.FootballThumbs[util.MaxMinRand(0, 9)]
		liveParams.Cateid = _const.FOOT_BALL_SPORT_ID
	}
	if match.SportId == _const.BASKET_BALL_SPORT_ID {
		liveParams.Thumb = global2.AutoLive.BasketballThumbs[util.MaxMinRand(0, 9)]
		liveParams.Cateid = _const.BASKET_BALL_SPORT_ID
	}

	if match.SportId == _const.CRICKET_BALL_SPORT_ID {
		liveParams.Thumb = global2.AutoLive.BasketballThumbs[util.MaxMinRand(0, 9)]
		liveParams.Cateid = _const.CRICKET_BALL_SPORT_ID
	}

	liveParams.Category = 2

	// _, _, _, anchorSecret, _, _ := base.Service.GetStreamInfo(user)
	streamKey := cache.GenStreamKey(user.Id)
	global2.GetRds().Set(streamKey, match.Stream, time.Duration(86400)*time.Second).Err()

	// log.Println("anchorSecret:", anchorSecret)

	// if anchorSecret == "" {
	// 	global.Log.Errorf("AuthLive error:%v", err)
	// 	return
	// }

	if checkExist(int(match.MatchId)) {
		return
	}

	l, e := base.Service.StartLive(&liveParams, user, &api_models.LivePlugins{
		LiveStatus: int(cache.StartLive),
		PullFlvUrl: match.UhdLink,
		PullUrl:    match.UhdLink,
		Platform:   3,
	})
	log.Println("l:", l)
	log.Println("e:", e)
	if e != nil {
		global2.Log.Errorf("AuthLive error:%v", err)
		return
	}

	global2.Sport().Model(&models_sports.MatchLive{}).Where("match_id=?", match.MatchId).Update("auto_live", 2)

	// 创建聊天群组
	p := &protobuf.CreateGroupReq{AnchorId: int32(user.Id), UserId: int32(user.Id), GroupName: cast.ToString(match.MatchId)}
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	grpc_client.GrpcTencentImClient.CreteGroup(ctx, p)
}

func checkExist(matchid int) bool {
	var lives *models_live.Live
	err := global2.Live().Model(&models_live.Live{}).Where("matchid = ? and anchorid in (?)", matchid, global2.AutoLive.LiveIDs).First(&lives).Error
	if err != nil {
		global2.Log.Error("AutoLive error : ", err)
		return false
	}
	if lives.Liveid > 0 {
		return true
	}

	return false
}

func endLive(matchID, categoryID, anchorID int) {
	if matchID <= 0 {
		return
	}
	var match *models_sports.MatchTempSchedule
	err := global2.Sport().Where("match_id=? and sport_id=?", matchID, categoryID).First(&match).Error
	if err != nil {
		global2.Log.Errorf("AuthLive endLive error:%v", err)
		// return
	}
	if match.MatchStatus >= 3 {
		err = services.EndLive(anchorID)
		if err != nil {
			global2.Log.Error("AutoLive endLive error : ", err)
			return
		}
	}
}
